import Vue from 'vue'
import Vuex from 'vuex'

import tim from '@/tim-init'
import TIM from 'tim-js-sdk'

import { showInfo } from '@/util/message'
import { titleNotify } from '@/util'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    userID: 'test1',
    userSig: 'eJyrVgrxCdZLrSjILEpVsjI2MwACHbBYWWqRkpWSkZ6BEoRfnJKdWFCQmQIUNDQxMDA2NDIyM4HKZaak5pVkpmWCtZSkFpcYwjRlpgNFnJKzo8xC3IOiInJdE83T9S0SLS0tTIMqyl3c8wwyzcyiHAuM/QKqytIjLWJKgUanQHWXZOYCHWVoamFsYmBoYGZRCwD3sDHl',
    rtcUserSig: 'eJw1jtEKgjAUht9l1yE7Tm34AJERQTYkpJtocxzEGjqXLXr3htm5+7+f7+e8idifIjUZ7BXJWUbDrWbmVE9yEkeU/PIg26sxKAOEhFIGGWTp0qFUd4sNzopVg4W/hDqQxpvDWRdH0Y1+493Oakd5y8u1qpJKiJp5uZ3q26t8PC9jmJaLbbELT0HKWUIBWPz5AmULM9k=',
    // sdk是否准备就绪
    isSdkReady: false,
    // 当前用户信息
    currentUserProfile: {},
    currentConversation: {},
    currentMessageList: [],
    nextReqMessageID: '',
    isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
    conversationList: [],
    videoRoomId: 0,
    isBusy: false,
    intervalID: null,
    current: null
  },
  getters: {
    toAccount: state => {
      if (!state.currentConversation || !state.currentConversation.conversationID) {
        return ''
      }
      switch (state.currentConversation.type) {
        case 'C2C':
          return state.currentConversation.conversationID.replace('C2C', '')
        case 'GROUP':
          return state.currentConversation.conversationID.replace('GROUP', '')
        default:
          return state.currentConversation.conversationID
      }
    },
    currentConversationType: state => {
      if (!state.currentConversation || !state.currentConversation.type) {
        return ''
      }
      return state.currentConversation.type
    },
    hidden: () => {
      if (typeof document.hasFocus !== 'function') {
        return document.hidden
      }
      return !document.hasFocus()
    },
    // 当前会话的未读消息
    totalUnreadCount: (state, getters) => {
      const result = state.conversationList.reduce((count, conversation) => {
        // 当前会话不计算总未读
        if (!getters.hidden && state.currentConversation.conversationID === conversation.conversationID) {
          return count
        }
        return count + conversation.unreadCount
      }, 0)
      titleNotify(result)
      return result
    },
    // 用于当前会话的图片预览
    imgUrlList: state => {
      return state.currentMessageList
          .filter(message => message.type === TIM.TYPES.MSG_IMAGE && !message.isRevoked) // 筛选出没有撤回并且类型是图片类型的消息
          .map(message => message.payload.imageInfoArray[0].url)
    }
  },
  mutations: {
    setSdkReady(state, status) {
      state.isSdkReady = status
    },
    updateCurrentUserProfile(state, userProfile) {
      state.currentUserProfile = userProfile
    },
    /**
     * 更新当前会话
     * 调用时机: 切换会话时
     * @param {Object} state
     * @param {Conversation} conversation
     */
    updateCurrentConversation(state, conversation) {
      state.currentConversation = conversation
      state.currentMessageList = []
      state.nextReqMessageID = ''
      state.isCompleted = false
    },
    /**
     * 更新会话列表
     * 调用时机：触发会话列表更新事件时。CONVERSATION_LIST_UPDATED
     * @param {Object} state
     * @param {Conversation[]} conversationList
     */
    updateConversationList(state, conversationList) {
      state.conversationList = conversationList
    },
    /**
     * 重置当前会话
     * 调用时机：需要重置当前会话时，例如：当前会话是一个群组，正好被踢出群时（被踢群事件触发），重置当前会话
     * @param {Object} state
     */
    resetCurrentConversation(state) {
      state.currentConversation = {}
    },
    /**
     * 将消息插入当前会话列表
     * 调用时机：收/发消息事件触发时
     * @param {Object} state
     * @param {Message[]|Message} data
     * @returns
     */
    pushCurrentMessageList(state, data) {
      // 还没当前会话，则跳过
      if (!state.currentConversation.conversationID) {
        return
      }
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.conversationID === state.currentConversation.conversationID)
        state.currentMessageList = [...state.currentMessageList, ...result]
      } else if (data.conversationID === state.currentConversation.conversationID) {
        state.currentMessageList = [...state.currentMessageList, data]
      }
    },
    /**
     * 从当前消息列表中删除某条消息
     * @param {Object} state
     * @param {Message} message
     */
    removeMessage(state, message) {
      const index = state.currentMessageList.findIndex(({ ID }) => ID === message.ID)
      if (index >= 0) {
        state.currentMessageList.splice(index, 1)
      }
    },
    reset(state) {
      Object.assign(state, {
        currentConversation: {},
        currentMessageList: [],
        nextReqMessageID: '',
        isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
        conversationList: []
      })
    },
    genVideoRoomId(state, videoRoomId) {
      if (videoRoomId) {
        state.videoRoomId = videoRoomId
      } else {
        state.videoRoomId = Math.ceil(Math.random() * (2 ** 32 - 1))
      }
    },
    setBusy(state, status) {
      state.busy = status
    },
    startComputeCurrent(state) {
      state.intervalID = setInterval(() => {
        state.current = Date.now()
      }, 500)
    },
    stopComputeCurrent(state) {
      state.intervalID && clearInterval(state.intervalID)
      state.intervalID = null
    },
  },
  actions: {
    /**
     * 获取消息列表
     * 调用时机：打开某一会话时或下拉获取历史消息时
     * @param {Object} context
     * @param {String} conversationID
     */
    getMessageList({ state }, conversationID) {
      if (state.isCompleted) {
        showInfo('已经没有更多的历史消息了哦')
        return
      }
      const { nextReqMessageID, currentMessageList } = state
      tim.getMessageList({ conversationID, nextReqMessageID, count: 15 }).then(imResponse => {
        // 更新messageID，续拉时要用到
        state.nextReqMessageID = imResponse.data.nextReqMessageID
        state.isCompleted = imResponse.data.isCompleted
        // 更新当前消息列表，从头部插入
        state.currentMessageList = [...imResponse.data.messageList, ...currentMessageList]
      })
    },
    /**
     * 切换会话
     * 调用时机：切换会话时
     * @param {Object} context
     * @param {String} conversationID
     */
    checkoutConversation({ state, commit, dispatch }, conversationID) {
      // 1.切换会话前，将切换前的会话进行已读上报
      if (state.currentConversation.conversationID) {
        const prevConversationID = state.currentConversation.conversationID
        tim.setMessageRead({ conversationID: prevConversationID })
      }
      // 2.待切换的会话也进行已读上报
      tim.setMessageRead({ conversationID })
      // 3. 获取会话信息
      const promise = tim.getConversationProfile(conversationID)
      if (!promise) {
        // commit('updateCurrentConversation', {
        //   conversationID,
        //   type: 'C2C',
        //   userProfile: {},
        //   groupProfile: {}
        // })
        return
      }
      promise.then(({ data }) => {
        console.log(data);
        // 3.1 更新当前会话
        commit('updateCurrentConversation', data.conversation)
        // 3.2 获取消息列表
        dispatch('getMessageList', conversationID)
        return Promise.resolve()
      });
    },
    // 退出登录
    logout({ state, commit }) {
      // 若有当前会话，在退出登录时已读上报
      if (state.currentConversation.conversationID) {
        tim.setMessageRead({ conversationID: state.currentConversation.conversationID })
      }
      tim.logout().then(() => {
        commit('stopComputeCurrent')
        commit('reset')
      })
    }
  }
})
